package main

import (
        "bufio"
        "fmt"
        "net"
        "os"
        "strings"

        "golang.org/x/crypto/ssh"
)

func main() {
        file, err := os.Open("servers.txt")
        if err != nil {
                fmt.Println("无法打开文件:", err)
                return
        }
        defer file.Close()

        scanner := bufio.NewScanner(file)
        validIPs := make(map[string]string)
        passwords := []string{"P@ssw0rd123@", "Gd!By@way#0828", "gdbyway@123", "123456"}

        for scanner.Scan() {
                ip := strings.TrimSpace(scanner.Text())

                for _, password := range passwords {
                        if connect(ip, password) {
                                validIPs[ip] = password
                                break
                        }
                }
        }

        if err := scanner.Err(); err != nil {
                fmt.Println("读取文件时出现错误:", err)
                return
        }

        f, err := os.Create("ipPwd.txt")
        if err != nil {
                fmt.Println("无法创建文件:", err)
                return
        }
        defer f.Close()

        for ip, password := range validIPs {
                f.WriteString(ip + " " + password + "\n")
        }

        fmt.Println("已写入ipPwd.txt文件")
}

func connect(ip, password string) bool {
        hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
                return nil
        }

        config := &ssh.ClientConfig{
                User:            "root",
                Auth:            []ssh.AuthMethod{ssh.Password(password)},
                HostKeyCallback: hostKeyCallback,
        }

        conn, err := ssh.Dial("tcp", ip+":22", config)
        if err != nil {
                fmt.Println("连接到", ip, "时发生错误:", err)
                return false
        }
        defer conn.Close()

        fmt.Printf("连接成功: %s %s\n", ip, password)
        return true
}
